<template>
  <div>
    <!--    <el-button type="primary" @click="delrouterall()">click</el-button>-->


    <div style="margin: 10px 0">
      <el-button size="small" type="primary" style="margin: 0 10px" @click="showNewForm">新增<i
          class="el-icon-circle-plus"></i></el-button>
      <!--      <el-button type="primary" style="margin: 0 10px" @click="handleDelBatch">批量导入<i-->
      <!--          class="el-icon-upload"></i></el-button>-->
      <!--      <el-upload-->
      <!--          :show-file-list="false"-->
      <!--          style="display: inline-block"-->
      <!--          class="upload-demo"-->
      <!--          action="xx"-->
      <!--          :http-request="uploadFile"-->
      <!--          ref="upload"-->
      <!--      >-->
      <!--        <el-button size="small" type="primary" style="margin: 10px 10px">批量导入<i-->
      <!--            class="el-icon-upload"></i></el-button>-->
      <!--      </el-upload>-->
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定删除吗？"
          @confirm="handleDelBatch"
      >
        <el-button size="small" type="danger" slot="reference" style="margin: 10px 10px">
          批量删除
          <i class="el-icon-remove-outline"></i>
        </el-button>
      </el-popconfirm>
      <div style="float: right">
        <el-cascader
            style="margin-left: 10px; width: 255px"
            placeholder="请选择单位"
            ref="dwref"
            v-model="dwid"
            @change="dwchange"
            :options="dwoptions"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"
            clearable>
        </el-cascader>
<!--        <el-select style="margin-left: 20px" v-model="devtype" clearable filterable placeholder="请选择设备类型">-->
<!--          <el-option-->
<!--              v-for="item in devtypeArr"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id">-->
<!--          </el-option>-->
<!--        </el-select>-->
        <el-input style="width: 200px; margin: 0 10px 0 10px" placeholder="请输入井号" suffix-icon="el-icon-search"
                  v-model="devname"/>

        <el-button type="primary" @click="search">搜索</el-button>
      </div>
    </div>


    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formRules" ref="form">
        <el-form-item label="井号" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.jh" autocomplete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="设备名" :label-width="formLabelWidth" prop="name">-->
<!--          <el-input v-model="form.name" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="单位" :label-width="formLabelWidth" prop="dwid">
          <el-cascader
              style=" width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="form.dwid"
              @change="dwchange"
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="设备类型" :label-width="formLabelWidth" prop="devtype" >
          <el-select style="" v-model="form.devtype" clearable filterable placeholder="请选择设备类型" :disabled="true">
            <el-option
                v-for="item in devtypeArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="IP" :label-width="formLabelWidth" prop="ip">
          <el-input v-model="form.ip" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="寄存器类型" :label-width="formLabelWidth" prop="regtype">
          <el-select v-model="form.regtype" placeholder="请选择寄存器类型" @change="handleNewSelChange">
            <el-option label="线圈" :value="0"></el-option>
            <el-option label="离散输入" :value="1"></el-option>
            <el-option label="输入寄存器" :value="3"></el-option>
            <el-option label="保持寄存器" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据类型" :label-width="formLabelWidth" prop="regdatatp">
          <el-select v-model="form.regdatatp" placeholder="请选择数据类型">
            <el-option
                v-for="item in form.datatypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="寄存器地址" :label-width="formLabelWidth" prop="location">
          <el-input v-model="form.location" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editform" :rules="editFormRules" ref="editform">
<!--        <el-form-item label="设备名称" :label-width="formLabelWidth" prop="name">-->
<!--          <el-input v-model="editform.name" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="井号" :label-width="formLabelWidth" prop="name">
          <el-input v-model="editform.jh" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="单位" :label-width="formLabelWidth" prop="dwid">
          <el-cascader
              emitPath: false
              style=" width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="editform.dwid"
              @change="dwchange"
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id' }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="设备类型" :label-width="formLabelWidth" prop="devtype">
          <el-select style="" v-model="editform.devtype" clearable filterable placeholder="设备类型"
                     disabled>
            <el-option
                v-for="item in devtypeArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="IP" :label-width="formLabelWidth" prop="ip">
          <el-input v-model="editform.ip" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="寄存器类型" :label-width="formLabelWidth" prop="regtype">
          <el-select v-model="editform.regtype" placeholder="请选择寄存器类型" @change="handleEditSelChange">
            <el-option label="线圈" :value="0"></el-option>
            <el-option label="离散输入" :value="1"></el-option>
            <el-option label="输入寄存器" :value="3"></el-option>
            <el-option label="保持寄存器" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据类型" :label-width="formLabelWidth" prop="regdatatp">
          <el-select v-model="editform.regdatatp" placeholder="请选择数据类型">
            <el-option
                v-for="item in editform.datatypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="寄存器地址" :label-width="formLabelWidth" prop="location">
          <el-input v-model="editform.location" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEidt">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="复制" :visible.sync="copyFormVisible" width="20%">
      <el-form :model="copyform" :rules="copyFormRules" ref="copyform">
        <el-form-item label="复制数量" :label-width="formLabelWidth" prop="count">
<!--          <el-input v-model.number="copyform.count" autocomplete="off"></el-input>-->
          <el-input-number v-model="copyform.count" controls-position="right" @change="handleCopyformCountChange" :min="1" :max="50"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCopy">确 定</el-button>
      </div>
    </el-dialog>

    <el-table ref="table" @selection-change="handleSelectionChange" :data="tableData"
              style="margin: 10px; width: 1600px" border stripe>
      <el-table-column width="50" type="selection">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>

      <el-table-column prop="id" label="ID" width="60" v-if="false">
      </el-table-column>
<!--      <el-table-column prop="name" label="设备名" width="200">-->
<!--      </el-table-column>-->
      <el-table-column prop="jh" label="井号" width="100">
      </el-table-column>
      <el-table-column prop="dwObj.dwname" label="单位" width="200">
      </el-table-column>
      <el-table-column prop="devtypeObj.name" label="设备类型" width="200">
      </el-table-column>
      <el-table-column prop="ip" label="IP" width="150">
      </el-table-column>
      <el-table-column label="寄存器类型" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.regtype === 0">线圈</span>
          <span v-if="scope.row.regtype === 1">离散输入</span>
          <span v-if="scope.row.regtype === 3">输入寄存器</span>
          <span v-if="scope.row.regtype === 4">保持寄存器</span>
        </template>
      </el-table-column>
      <el-table-column label="数据类型" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.regdatatp === 2">16位无符号整数</span>
          <span v-if="scope.row.regdatatp === 3">16位整数</span>
          <span v-if="scope.row.regdatatp === 4">32位无符号整数</span>
          <span v-if="scope.row.regdatatp === 5">32位整数</span>
          <span v-if="scope.row.regdatatp === 8">32位float</span>
          <span v-if="scope.row.regdatatp === 1">bool</span>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="寄存器地址" width="200">
      </el-table-column>

      <!--      <el-table-column prop="role.roleName" label="角色" width="200">-->
      <!--      </el-table-column>-->
      <el-table-column prop="#" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="showEditForm(scope.row)">编辑<i
              class="el-icon-edit"></i></el-button>
          <el-button size="small" type="primary" @click="showCopyForm(scope.row)">复制<i
              class="el-icon-edit"></i></el-button>
          <!--              <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>-->
          <el-popconfirm
              style="margin: 0 10px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button size="small" type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>
<!--          <router-link :to="{-->
<!--            path: '/jc/dev/ywxxwh/',-->
<!--            query:{-->
<!--              id: scope.row.id-->
<!--            }-->
<!--          }">-->
<!--            <el-button size="small" type="success">业务配置 <i class="el-icon-set-up"></i>-->
<!--            </el-button>-->
<!--          </router-link>-->
        </template>
      </el-table-column>
    </el-table>


    <div class="block" style="padding: 5px">
      <el-pagination

          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100,500,1000]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>

</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";

import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";


export default {
  created() {
    service.get('/dw/getAll', {}).then(
        response => {
          if (response.data.code == 20000) {
            this.dwoptions = response.data.data
          }
        }
    )
    service.get('/devtype/getAll', {}).then(
        response => {
          if (response.data.code == 20000) {
            this.devtypeArr = response.data.data
          }
        }
    )
    this.load();
  },
  data() {
    return {
      jh: null,
      dwoptions: [],
      dwval: [],
      devname: null,
      dwid: null,
      devtype: null,
      devtypeArr: [],
      tableData: [],
      selectedRows: [], // 用来存储选中行的数据
      pageSize: 10,
      total: 100,
      currentPage: 1,
      dialogFormVisible: false,
      editFormVisible: false,
      copyFormVisible: false,
      form: {
        jh: null,
        name: '',
        ip: '',
        dwid: '',
        devtype: 10,
        regtype: null,
        regdatatp: null,
        location: null,
        datatypes: []
      },
      editform: {
        jh: null,
        id: null,
        name: '',
        ip: '',
        dwid: '',
        devtype: 10,
        regtype: null,
        regdatatp: null,
        location: null,
        datatypes: []
      },
      copyform: {
        id: null,
        count: null
      },
      formRules: {
        jh: [
          {required: true, message: '请输入设备名', trigger: 'blur'}],
        ip: [
          {required: true, message: '请输入IP', trigger: 'blur'}],
        dwid: [
          {required: true, message: '请选择单位', trigger: 'blur'},
        ],
        devtype: [
          {required: true, message: '请选择设备类型', trigger: 'blur'},
        ]
      },
      editFormRules: {
        jh: [
          {required: true, message: '请输入设备名', trigger: 'blur'}],
        ip: [
          {required: true, message: '请输入IP', trigger: 'blur'}],
        dwid: [
          {required: true, message: '请选择单位', trigger: 'blur'},
        ],
        devtype: [
          {required: true, message: '请选择设备类型', trigger: 'blur'},
        ]
      },
      copyFormRules: {
        count: [
          {required: true, message: '请输入复制数量', trigger: 'blur'},
        ]
      },

      formLabelWidth: '120px'
    }
  },
  methods: {
    load() {
      service.get('/hsy/getpage', {
        params: {
          pagesize: this.pageSize,
          pagenum: this.currentPage,
          jh: this.jh,
          dwid: this.dwid == null ? null : (this.dwid.length == 0 ? null : this.dwid[this.dwid.length - 1]),
          // devtype: this.devtype,
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );


    },

    dwchange(dw) {
      console.log(this.editform.dwid)
    },

    handleSelectionChange(selection) {
      // console.log(selection)
      // this.selectedRows = selection.map(row => row._row);
      this.selectedRows = selection
      // console.log(this.selectedRows)
    },

    showNewForm() {
      this.form = {
        jh: null,
        name: '',
        ip: '',
        dwid: '',
        devtype: 10,
        regtype: null,
        regdatatp: null,
        location: null,
        datatypes: []
      }

      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs["form"].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    handleSave() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        let saveform = {}
        saveform.jh = this.form.jh
        saveform.name = this.form.name
        saveform.ip = this.form.ip
        saveform.dwid = this.form.dwid == null ? null : this.form.dwid[this.form.dwid.length - 1]
        saveform.devtype = this.form.devtype
        saveform.regtype = this.form.regtype
        saveform.regdatatp = this.form.regdatatp
        saveform.location = this.form.location
        service.post('/hsy/save', saveform).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.dialogFormVisible = false

            this.load()
          } else {
            this.$message.error("error")
            this.dialogFormVisible = false
          }
        })
      })

    },

    handleNewSelChange(val) {
      console.log(this.form.datatypes)
      if (val == 0 || val == 1) {//线圈 离散输入
        this.form.datatypes = [{id: 1, name: '布尔'}]

      } else if (val == 3 || val == 4) {//保持寄存器  输入寄存器
        this.form.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]

      }
      this.form.regdatatp = null
    },


    showEditForm(row) {
      // this.editform = {}
      this.editform.jh = row.jh
      this.editform.id = row.id
      this.editform.name = row.name
      this.editform.ip = row.ip
      this.editform.regtype = row.regtype
      this.editform.location = row.location
      console.log(this.editform)
      if (this.editform.regtype == 1 || this.editform.regtype == 0) {
        this.editform.datatypes = [{id: 1, name: '布尔'}]
      } else if (this.editform.regtype == 3 || this.editform.regtype == 4) {
        this.editform.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]
      }
      this.editform.regdatatp = row.regdatatp
      if (row.dwObj)
        this.editform.dwid = row.dwObj.id
      else
        this.editform.dwid = null
      if (row.devtypeObj)
        this.editform.devtype = row.devtypeObj.id
      else
        this.editform.devtype = null
      service.get('/dw/getPathByid', {
        params: {
          id: this.editform.dwid
        }
      }).then(
          response2 => {
            if (response2.data.code == 20000) {
              this.editform.dwid = response2.data.data
              this.editFormVisible = true
              this.$nextTick(() => {
                this.$refs["editform"].clearValidate()
              })
            } else {
              this.$message.error(response2.data.message)
              throw new Error(response2.data.message)
            }
          }
      )
    },
    handleEditSelChange(val) {
      console.log(this.editform.datatypes)
      if (val == 0 || val == 1) {//线圈
        this.editform.datatypes = [{id: 1, name: '布尔'}]
      } else if (val == 3 || val == 4) {//保持寄存器
        this.editform.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]
      }
      this.editform.regdatatp = null
    },

    handleEidt() {
      this.$refs.editform.validate(valid => {
        if (!valid) {
          return
        }
        let editformTmp = {}
        editformTmp.id = this.editform.id
        editformTmp.jh = this.editform.jh
        editformTmp.name = this.editform.name
        editformTmp.devtype = this.editform.devtype
        editformTmp.ip = this.editform.ip
        editformTmp.dwid = this.editform.dwid[this.editform.dwid.length - 1]
        editformTmp.regtype = this.editform.regtype
        editformTmp.regdatatp = this.editform.regdatatp
        editformTmp.location = this.editform.location
        service.post('/hsy/edit', editformTmp).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.editFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.editdialogFormVisible = false
          }
        })
      })

    },
    showCopyForm(row) {
      // this.copyform = {}
      this.copyform.id = row.id
      this.copyform.count = 1
      this.copyFormVisible = true
      this.$nextTick(() => {//下次dom更新后延迟回调，否则没有copyform这个窗口
        this.$refs["copyform"].clearValidate()
      })
    },
    handleCopy() {
      this.$refs.copyform.validate(valid => {
        if (!valid) {
          return
        }
        service.get('/hsy/copy', {
          params: {
            id: this.copyform.id,
            count: this.copyform.count
          }
        }).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('复制成功!');
            this.load()
          } else {
            this.$message.error("复制失败！")
          }
        }).catch(error => {
          this.$message.error(error.message)
        })
        this.copyFormVisible = false
      })

    },
    handleCopyformCountChange(currentValue, oldValue){//似乎这里不需要，组件本身好像就只能接受数字
      console.log(this.copyform.count)
      // if(!/^[0-9]*$/.match(currentValue) ){
      //   this.$message.error("请输入正整数")
      //   this.copyform.count = oldValue
      // }
    },
    handleDel(id) {
      service.delete('/hsy?id=' + id).then(response => {
        this.$message.success('删除成功!');
        this.load()
      })
    },
    search() {
      this.currentPage = 1
      this.load()
    },
    handleDelBatch() {
      service.post('/hsy/delbatch', this.selectedRows).then(response => {
        if (response.data.code == 20000) {
          this.$message.success('删除成功!');
          this.load()
        } else {
          this.$message.error("error")
        }
      })
    },


  }
}
</script>

<style scoped>

</style>
